import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ItcoreImport } from '@shared/itcore/itcore.model';
import { itcoreService } from '@shared/itcore/services/itcore.service';
import { NzModalComponent } from 'ng-zorro-antd/modal';
import { NzUploadFile } from 'ng-zorro-antd/upload';
@Component({
  // tslint:disable-next-line: component-selector
  selector: 'itcore-import',
  template: `
  <button nz-button nzType="primary" (click)="this.IsShow = true">
    <span>{{ importOption.btnText || '导入' }}</span>
  </button>

  <nz-modal 
      [(nzVisible)]="IsShow"
      [nzTitle]="importOption.btnText || '导入'"
      (nzOnCancel)="handleCancelModal()"
      (nzOnOk)="handleUpload()"
      [nzOkDisabled]="fileList.length == 0"
      [nzOkText]="uploading ? '上传中...' : '开始上传'"
      [nzOkLoading]="uploading"
      nzMaskClosable="false"
      >
        <nz-upload [(nzFileList)]="fileList" [nzBeforeUpload]="beforeUpload" [nzFileType]="importOption.nzFileType">
          <button nz-button><i nz-icon nzType="upload"></i>选择文件</button>
        </nz-upload>
      </nz-modal>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ItcoreImportComponent {
  constructor(private itcore: itcoreService, private cdf: ChangeDetectorRef) { }

  // 传入的 配置
  @Input() importOption: ItcoreImport;

  // 传出的成功回调
  @Output() importSuccess = new EventEmitter<any>();

  @Output() importError = new EventEmitter<any>();

  uploading = false;
  fileList: NzUploadFile[] = [];
  IsShow: boolean;
  @ViewChild('uploadModal', { static: false }) uploadModal: NzModalComponent;
  handleCancelModal() {
    this.IsShow = false;
    this.uploading = false;
    this.fileList = [];
  }

  // tslint:disable-next-line: deprecation
  beforeUpload = (file: NzUploadFile): boolean => {
    if (this.importOption.IsUpdateSingle) {
      this.fileList = [];
      this.fileList = new Array(file);
    } else {
      this.fileList = this.fileList.concat(file);
    }
    return false;
  }

  handleUpload(): void {
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    if (this.importOption.IsUpdateSingle) {
      formData.append('file', this.fileList[0] as any);
    } else {
      this.fileList.forEach((file: any) => {
        formData.append('files[]', file);
      });
    }
    this.uploading = true;
    this.itcore.http.post(this.importOption.url, formData).subscribe(
      (res) => {
        if (res.Type === 200) {
          this.fileList = [];
          this.itcore.success(this.importOption.successText || '导入成功！');
          this.IsShow = false;
          this.importSuccess.emit();
        }
        this.uploading = false;
        this.cdf.detectChanges();
      },
      () => {
        this.uploading = false;
        this.itcore.error(this.importOption.errorText || '导入失败！');
        this.importError.emit();
      },
    );
  }
}
